package org.jumiz.framework.mysql.wrapper;

import org.jumiz.framework.base.reflect.*;
import org.jumiz.framework.base.wrapper.QueryWrapper;

/**
 * mysql 查询构建
 * @author jumiz
 */
public class MysqlQueryWrapper<T> extends QueryWrapper<T> {

    public MysqlQueryWrapper(Class<T> tClass) {
        super(tClass);
    }

    private StringBuilder whereSql = new StringBuilder();

    private boolean firstWhere = true;

    @Override
    public QueryWrapper<T> eq(SFunction<T, String> column, Object value) {
        try {
            SFunctionDefinition<T> definition = column.definition(column);
            String fieldName = definition.getFieldName();
            SqlDefinition sqlDefinition = super.getSqlDefinition();
            ColumnDefinition columnDefinition = sqlDefinition.getColumnDefinition().getByFieldName(fieldName);
            if (firstWhere) {
                whereSql.append(SqlKeyword.WHERE);
                firstWhere = false;
            } else {
                whereSql.append(" ").append(SqlKeyword.AND);
            }
            whereSql.append(" ").append(columnDefinition.getColumnName()).append(" = ").append(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.eq(column, value);
    }

    @Override
    public String toSqlString() {
        return new StringBuilder()
                .append(SqlKeyword.SELECT)
                .append(" ")
                .append(super.getSqlDefinition().getColumnDefinition().getSqlColumns())
                .append(" ")
                .append(SqlKeyword.FROM)
                .append(" ")
                .append(super.getSqlDefinition().getTableName())
                .append(whereSql.length() > 0 ? " " + whereSql.toString() : "").toString();
    }
}
